def get_sso_info(content):
    import re
    # get servertime, nonce, pcid
    matchobj = re.search(r'\((.*)\)', content)
    
    return eval(matchobj.group(1))

def get_sso_passwd(sso_info, ps):
    from hashlib import sha1
    ps = sha1(sha1(ps).hexdigest()).hexdigest()

    mix_sso_pw = sha1(
        ps + str(sso_info['servertime']) + 
        str(sso_info['nonce'])
    ).hexdigest()

    return mix_sso_pw
    
def sso_login(usernameB64, servertime, nonce, sso_mix_ps):
    import requests

    _ = servertime
    callback = 'sinaSSOController.loginCallBack'
    cdult = 2
    client = 'ssologin.js(v1.3.22)'
    ct = 1800
    domain = 'weibo.com'
    door = ''   
    encoding = 'UTF-8'
    entry = 'openapi'
    gateway = 1
    nonce = nonce
    prelt = 417
    pwencode ='wsse'
    returntype = 'TEXT'
    s = 1
    savestate = 0
    servertime = servertime
    service = 'miniblog'
    sp = sso_mix_ps
    su = usernameB64
    useticket = 1
    vsnf = 1
    vsnval = '' 
    url = 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack'

    r = requests.post('https://login.sina.com.cn/sso/login.php', data=locals())
    return r

def get_authenticate_code(params, headers):
    import requests 

    action = 'submit'
    client_id = params['client_id']
    isLoginSina = ''
    passwd = '' 
    redirect_uri = 'http://code.google.com/p/linux-terminal-client/'
    regCallback = ''
    response_type = 'code'
    state = '' 
    ticket = params['ticket']
    userId = params['userId']
    withOfficalFlag = 0

    r = requests.post('https://api.weibo.com/oauth2/authorize', data=locals(), headers=headers)

    import re
    # get code from url
    matchobj = re.search(r'=(.*)$', r.url)
    
    return matchobj.group(1)

def sina_sso(authorize_url):
    from config import APP_KEY, USERNAME, PASSWD
    import requests
    from bs4 import BeautifulSoup
    import base64
    
    usernameB64 = base64.encodestring(USERNAME)

    sso_url = 'http://login.sina.com.cn/sso/prelogin.php?' + \
              'entry=openapi&callback=sinaSSOController.' + \
              'preloginCallBack&user='+ usernameB64 +'&client=ssologin.js'
    r = requests.get(sso_url)
    # get server time etc
    sso_info = get_sso_info(r.content)

    # sso login
    sso_pw = get_sso_passwd(sso_info, PASSWD)

    r = sso_login(usernameB64, sso_info['servertime'], sso_info['nonce'], sso_pw)
    
    # final shot
    params = {}
    params['ticket'] = get_sso_info(r.content)['ticket']
    params['userId'] = USERNAME
    params['client_id'] = APP_KEY
    
    headers = {'Referer': authorize_url}

    auth_code = get_authenticate_code(params, headers)
    return auth_code
